<template>
  <a-anchor tag="a-anchor" ref="dragRef">
    <a-anchor-link style="font-size: 12px" v-for="element in value" :key="element[fieldNames.href]" :href="'#'+element[fieldNames.href]" :title="element[fieldNames.title]"></a-anchor-link>
  </a-anchor>
</template>

<script>
export default {
  name: "ExDragAnchor",
}
</script>
<script setup>
import Sortable from 'sortablejs'
import {useAttrs, onMounted, ref, onBeforeUnmount} from "vue";
const dragRef = ref()
const attrs = useAttrs()
const props = defineProps({
  value:Array,
  fieldNames:{
    type:Object,
    default:{
      href:'href',
      title:'title',
    }
  }
})
let sortable = null
onMounted(()=>{
  let el = dragRef.value.$el.querySelectorAll('.ant-anchor')[0]
  sortable = Sortable.create(el, {
    animation: 1000,
    handle: '.ant-anchor-link',
    onEnd: evt => {
      var newIndex = evt.newIndex-1
      var oldIndex = evt.oldIndex-1
      const targetRow = props.value.splice(oldIndex, 1)[0]
      props.value.splice(newIndex, 0, targetRow)
    }
  })
})
onBeforeUnmount((e) => {
  if (sortable) {
    sortable.destroy()
  }
})
</script>

<style scoped>

</style>